const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('../frontend'));

// 数据库初始化
const db = new sqlite3.Database('todos.db');

db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS todos (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        completed BOOLEAN DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )`);
});

// API路由

// 获取所有待办事项
app.get('/api/todos', (req, res) => {
    const { search, completed } = req.query;
    let query = 'SELECT * FROM todos';
    let params = [];

    if (search || completed !== undefined) {
        query += ' WHERE';
        const conditions = [];
        
        if (search) {
            conditions.push('title LIKE ?');
            params.push(`%${search}%`);
        }
        
        if (completed !== undefined) {
            conditions.push('completed = ?');
            params.push(completed === 'true' ? 1 : 0);
        }
        
        query += ' ' + conditions.join(' AND ');
    }
    
    query += ' ORDER BY created_at DESC';
    
    db.all(query, params, (err, rows) => {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        res.json(rows);
    });
});

// 创建新的待办事项
app.post('/api/todos', (req, res) => {
    const { title } = req.body;
    
    if (!title || title.trim() === '') {
        res.status(400).json({ error: '标题不能为空' });
        return;
    }

    db.run('INSERT INTO todos (title) VALUES (?)', [title.trim()], function(err) {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        
        db.get('SELECT * FROM todos WHERE id = ?', [this.lastID], (err, row) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json(row);
        });
    });
});

// 更新待办事项
app.put('/api/todos/:id', (req, res) => {
    const { id } = req.params;
    const { title, completed } = req.body;
    
    let query = 'UPDATE todos SET';
    let params = [];
    let updates = [];
    
    if (title !== undefined) {
        updates.push('title = ?');
        params.push(title.trim());
    }
    
    if (completed !== undefined) {
        updates.push('completed = ?');
        params.push(completed ? 1 : 0);
    }
    
    if (updates.length === 0) {
        res.status(400).json({ error: '没有提供要更新的字段' });
        return;
    }
    
    query += ' ' + updates.join(', ') + ' WHERE id = ?';
    params.push(id);
    
    db.run(query, params, function(err) {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        
        if (this.changes === 0) {
            res.status(404).json({ error: '待办事项不存在' });
            return;
        }
        
        db.get('SELECT * FROM todos WHERE id = ?', [id], (err, row) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json(row);
        });
    });
});

// 删除待办事项
app.delete('/api/todos/:id', (req, res) => {
    const { id } = req.params;
    
    db.run('DELETE FROM todos WHERE id = ?', [id], function(err) {
        if (err) {
            res.status(500).json({ error: err.message });
            return;
        }
        
        if (this.changes === 0) {
            res.status(404).json({ error: '待办事项不存在' });
            return;
        }
        
        res.json({ message: '删除成功' });
    });
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
